import SparkMD5 from 'spark-md5'
import {DEFAULT_SIZE} from "@/const/Const"

const generationMd5 = (file, chunkSize = DEFAULT_SIZE, chunkCallback) => {

    let paused = false; // 用来控制暂停
    let canceled = false; // 用来控制取消
    let resumer;
    let rejectFunc;
    // 暂停函数
    function pause() {
        paused = true;
    }

    // 恢复函数
    function resumeProcessing() {
        paused = false;
        resumer();
    }

    // 取消函数
    function cancel() {
        canceled = true;
        rejectFunc("取消生成md5")
    }

     let promise = new Promise((resolve, reject) => {
         rejectFunc=reject;
        const startMs = new Date().getTime();
        let blobSlice =
            File.prototype.slice ||
            File.prototype.mozSlice ||
            File.prototype.webkitSlice;
        let chunks = Math.ceil(file.size / chunkSize);
        let currentChunk = 0;
        let spark = new SparkMD5.ArrayBuffer(); //追加数组缓冲区。
        let fileReader = new FileReader(); //读取文件


        fileReader.onload = function (e) {

            if (canceled) return; // 如果被取消，跳过后续操作

            spark.append(e.target.result);
            currentChunk++;
            if (currentChunk < chunks) {
                if (paused) {
                    resumer=loadNext
                } else {
                    loadNext();
                }
            } else {
                const md5 = spark.end(); //完成md5的计算，返回十六进制结果。
                console.log('文件md5计算结束，总耗时：', (new Date().getTime() - startMs) / 1000, 's')
                resolve(md5);
            }
        };
        fileReader.onerror = function (e) {
            reject(e);
        };

        function loadNext() {
            console.log('当前part number：', currentChunk, '总块数：', chunks);
            let start = currentChunk * chunkSize;
            let end = start + chunkSize;
            (end > file.size) && (end = file.size);
            fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
            if (chunkCallback) {
                chunkCallback(currentChunk + 1, chunks)
            }
        }

        loadNext();
    });

    return {promise,pause,resumeProcessing,cancel}
}

export default generationMd5
